package cn.imokay.stopthread;

import org.junit.Test;

/**
 * run方法有sleep，如果执行过程中，每次循环都会sleep或者wait
 * 无需每次迭代都近行判断<code>!Thread.currentThread().isInterrupted()</code>
 * 因为sleep的时候会自动判断
 * <p>
 * 当try catch在循环中时，捕获异常后没有进行中断，即使增加了<code>!Thread.currentThread().isInterrupted()</code>判断，也无法中断，因为sleep时isInterrupted被重置了
 * <p>
 * 传递中断，恢复中断，不应屏蔽中断
 */
public class RightWayStopThreadWithSleepDealInterrupt {

    @Test
    public void interruptTransfer() throws InterruptedException {
        /**
         * 中断传递，调用的方法中sleep时被中断，将中断传递到顶层函数
         */
        Runnable r = () -> {
            int num = 0;

            while (num <= 10000) {
                try {
                    doSomethingiInterruptTransfer(num);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                    System.out.println("调用的方法中没有处理中断，被传递到顶层方法来处理，顶层方式获取中断信号后，立马停止循环进行收尾");
                    break;
                }
                num++;

            }

            System.out.println("finished");
        };
        Thread thread = new Thread(r);
        thread.start();
        Thread.sleep(5000);
        thread.interrupt();
    }


    private  void doSomethingiInterruptTransfer(int num) throws InterruptedException {
        if (num % 100 == 0) {
            System.out.println(num + "是100的整数倍");
        }

        Thread.sleep(10);
    }




    @Test
    public void interruptRecover() throws InterruptedException {
        Runnable r = () -> {
            int num = 0;

            while ( num <= 10000) {
                doSomethingiInterruptRecover(num);
                num++;
                if (Thread.currentThread().isInterrupted()) {
                    System.out.println("顶层函数处理中断，收尾后结束线程");
                    break;
                }
            }

            System.out.println("finished");
        };
        Thread thread = new Thread(r);
        thread.start();
        Thread.sleep(5000);
        thread.interrupt();
    }


    private  void doSomethingiInterruptRecover(int num){
        if (num % 100 == 0) {
            System.out.println(num + "是100的整数倍");
        }

        try {
            Thread.sleep(10);
        } catch (InterruptedException e) {
            System.out.println("调用的方法中sleep时被中断，处理收尾工作后，恢复中断状态，让顶层函数处理中断");
            Thread.currentThread().interrupt();
        }
    }
}
